{% load static %}
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>设备管理</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
      /* ===== 新增背景设置 ===== */
    body {
      font-family:"Segoe UI",sans-serif;
      margin:0;
      min-height:100vh;
      /* 背景图片设置 */
      background: url('{% static "images/background.jpg" %}') no-repeat center center fixed;
      background-size: cover;
      position: relative;
    }
    /* 确保内容在遮罩层上方 */
    .wrapper {
      position: relative;
      z-index: 1;
      max-width:960px;
      margin:40px auto;
      background:#fff;
      padding:24px 32px;
      border-radius:16px;
      box-shadow:0 6px 18px rgba(0,0,0,.12);
    }

  h1{margin:0 0 24px;color:#2563eb;display:flex;align-items:center;font-size:26px}
  h1 i{margin-right:10px}

  details{border:1px solid #e5e7eb;border-radius:10px;margin-bottom:14px}
  summary{cursor:pointer;padding:12px 16px;font-size:17px;font-weight:600;
          background:#f9fafb;border-bottom:1px solid #e5e7eb;outline:none}

  .dev-row{display:flex;align-items:center;justify-content:space-between;
           padding:10px 16px;border-bottom:1px solid #f1f1f1}
  .dev-row:last-child{border-bottom:none}
  .dev-row .info{display:flex;align-items:center;gap:8px}
  .type-box{padding:2px 6px;background:#e5e7eb;border-radius:4px;font-size:12px}

  .tag{padding:2px 8px;border-radius:6px;font-size:12px;color:#fff}
  .online{background:#22c55e}.offline{background:#ef4444}.fault{background:#f59e0b}

  .icon-btn{background:none;border:none;color:#6b7280;font-size:18px;cursor:pointer}
  .icon-btn:hover{color:#111}

  form{margin-top:32px;display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:14px}
  input,select{padding:10px;border:1px solid #d1d5db;border-radius:8px;font-size:15px}
  input:focus,select:focus{border-color:#2563eb;box-shadow:0 0 0 2px rgba(37,99,235,.3);outline:none}

  .unit-wrapper{grid-column:1 / span 2;position:relative}
  .unit-wrapper input{width:100%;padding-right:3em}
  .unit-label{position:absolute;right:0.75em;top:50%;transform:translateY(-50%);
              color:#666;font-size:0.9em;pointer-events:none}
  .range-hint{grid-column:1/-1;font-size:12px;color:#888;margin-top:-8px;margin-bottom:10px}

  button.add{grid-column:1/-1;padding:12px;background:#2563eb;color:#fff;border:none;
             border-radius:10px;font-size:16px;cursor:pointer}
  button.add:hover{background:#1e40af}

  .nav{margin-top:26px;display:flex;gap:12px;justify-content:center}
  .nav a{padding:8px 18px;border-radius:8px;text-decoration:none;color:#fff;font-size:14px}
  .nav .home{background:#2563eb}.nav .users{background:#10b981}
  .nav .messages     { background:#f59e0b; }
  .nav a.logout{background:#ef4444}.nav a.logout:hover{background:#dc2626}
</style>
</head>
<body>
<div class="wrapper">
  <h1><i class="fas fa-tools"></i>设备管理</h1>

  <!-- 设备分组列表 -->
  <div id="deviceHolder">加载中…</div>

  <!-- 添加设备表单 -->
  <h2 style="margin:34px 0 16px;color:#2563eb"><i class="fas fa-plus-circle"></i> 添加设备</h2>
  <form id="addForm">
    <input id="devName" placeholder="设备名称(如：阳台灯)" required>
    <select id="devType" required>
      <option value="" disabled selected>选择类型</option>
      <option>空调</option>
      <option>加湿器</option>
      <option>空气净化器</option>
      <option>灯光</option>
    </select>

    <!-- 房间下拉由 Ajax 填充 -->
    <select id="devRoom" required>
      <option value="" disabled selected>加载房间中…</option>
    </select>

    <select id="devStatus" required>
      <option value="offline">离线</option>
      <option value="online">在线</option>
      <option value="fault">故障</option>
    </select>

    <div class="unit-wrapper">
      <input id="devValue" type="number" placeholder="初始控制值(可空)">
      <span id="unitLabel" class="unit-label"></span>
    </div>
    <div id="rangeHint" class="range-hint"></div>

    <button class="add" type="submit">添加设备</button>
  </form>

  <!-- 底部导航 -->
  <div class="nav">
    <a href="/user_manage/" class="users" style="display:none"><i class="fas fa-users-cog"></i> 用户管理</a>
    <a href="/index/" class="home"><i class="fas fa-home"></i> 控制首页</a>
    <a href="/monitor/messages/" class="messages"><i class="fas fa-envelope"></i>监控</a>
    <a href="#" class="logout" id="logoutBtn"><i class="fas fa-sign-out-alt"></i> 登出</a>
  </div>
</div>

<script>
/*=============== 全局工具 ===============*/
async function api(path, opt={}) {
  const res = await fetch(path, {...opt, headers:{'Content-Type':'application/json','Accept':'application/json'}});
  const txt = await res.text();
  let data={}; try{data = txt?JSON.parse(txt):{};}catch{}
  if(!res.ok) throw Error(data.message||res.statusText);
  return data;
}

/*=============== 房间列表 ===============*/
let roomMap = {};      // id -> name
async function loadRooms() {
  const select = document.getElementById('devRoom');
  try {
    const rooms = await api('/rooms/');
    roomMap = Object.fromEntries(rooms.map(r=>[r.room_id, r.name]));
    // 填充下拉
    select.innerHTML = '<option value="" disabled selected>选择位置</option>';
    rooms.forEach(r=>{
      select.insertAdjacentHTML('beforeend', `<option value="${r.room_id}">${r.name}</option>`);
    });
  } catch(e){
    select.innerHTML = '<option value="" disabled selected>加载失败</option>';
    alert('获取房间列表失败：'+e.message);
  }
}

/*=============== 设备列表 ===============*/
let devices = [];
async function loadDevices(){
  try{
    devices = await api('/devices/');
    renderDevices();
  }catch(e){ alert('加载设备失败：'+e.message); }
}

// 按 d.room_name 分组
function groupByRoom(list){
  return list.reduce((m, d) => {
    const room = d.room_name || '未知房间';
    (m[room] = m[room] || []).push(d);
    return m;
  }, {});
}

function renderDevices(){
  const holder = document.getElementById('deviceHolder');
  if(!devices.length){ holder.innerHTML='暂无设备'; return; }
  holder.innerHTML='';
  for(const [room,arr] of Object.entries(groupByRoom(devices))){
    holder.insertAdjacentHTML('beforeend',`
      <details open>
        <summary>${room}（${arr.length}）</summary>
        ${arr.map(rowHTML).join('')}
      </details>`);
  }
}

function rowHTML(d){
  return `
    <div class="dev-row" id="row-${d.device_id}">
      <div class="info">
        <i class="fas fa-microchip"></i>
        <span class="dev-name">${d.device_name}</span>
        <button class="icon-btn" onclick="editName('${d.device_id}','${d.device_name}')" title="编辑名称">
          <i class="fas fa-edit"></i>
        </button>
        <span class="type-box">${d.device_type}</span>
      </div>
      <div>
        <span class="tag ${d.status}">${{online:'在线',offline:'离线',fault:'故障'}[d.status]||d.status}</span>
        <button class="icon-btn" onclick="delDevice('${d.device_id}')" title="删除">
          <i class="fas fa-trash-alt"></i>
        </button>
      </div>
    </div>`;
}

/*=============== 删除设备 ===============*/
async function delDevice(id){
  if(!confirm('确定删除该设备？')) return;
  try{
    await api(`/devices/${id}/`, {method:'DELETE'});
    devices = devices.filter(d=>d.device_id!==id);
    renderDevices();
  }catch(e){ alert('删除失败：'+e.message); }
}

/*=============== 新增设备 ===============*/
document.getElementById('addForm').addEventListener('submit', async e=>{
  e.preventDefault();
  const body = {
    device_name  : devName.value.trim(),
    device_type  : devType.value,
    room         : Number(devRoom.value),   // 发送 room ID
    status       : devStatus.value,
    control_value: devValue.value ? Number(devValue.value) : null
  };
  try{
    await api('/devices/', {method:'POST', body:JSON.stringify(body)});
    alert('添加成功');
    e.target.reset();
    clearUnitAndRange();
    loadDevices();
  }catch(err){ alert('添加失败：'+err.message); }
});

/*=============== 单位 / 范围辅助 ===============*/
const unitMap = {
  '空调': {unit:'℃', min:16, max:30},
  '加湿器':{unit:'%', min:30, max:90},
  '空气净化器':{unit:'ppm', min:0, max:500},
  '灯光':{unit:'lux', min:100, max:1000}
};
const devType   = document.getElementById('devType');
const devValue  = document.getElementById('devValue');
const unitLabel = document.getElementById('unitLabel');
const rangeHint = document.getElementById('rangeHint');

devType.addEventListener('change', ()=>{
  clearUnitAndRange();
  const cfg = unitMap[devType.value];
  if(cfg){
    unitLabel.textContent = cfg.unit;
    devValue.min = cfg.min; devValue.max = cfg.max;
    rangeHint.textContent = `推荐范围：${cfg.min}${cfg.unit} ~ ${cfg.max}${cfg.unit}`;
  }
});
function clearUnitAndRange(){
  unitLabel.textContent = ''; rangeHint.textContent = '';
  devValue.removeAttribute('min'); devValue.removeAttribute('max');
}

/*=============== 重命名设备 ===============*/
async function editName(id, oldName){
  const newName = prompt('请输入设备新名称：', oldName);
  if(!newName || newName.trim()==='' || newName===oldName) return;
  try{
    await api(`/devices/${id}/`, {method:'PUT', body:JSON.stringify({device_name:newName.trim()})});
    devices = devices.map(d=>d.device_id==id?({...d,device_name:newName.trim()}):d);
    renderDevices();
    alert('名称更新成功');
  }catch(e){ alert('更新失败：'+e.message); }
}

/*=============== 导航／权限／登出 ===============*/
(()=>{
  if(localStorage.getItem('userRole')==='管理员')
    document.querySelector('.nav .users').style.display='inline-block';
  logoutBtn.onclick = e=>{
    e.preventDefault();
    ['authToken','currentUser','userRole','permissionLevel'].forEach(k=>localStorage.removeItem(k));
    location.href='/';
  };
})();

/*=============== 入口 ===============*/
(async ()=>{
  await loadRooms();   // 先拿房间再渲染下拉
  await loadDevices(); // 然后加载设备
})();
</script>
</body>
</html>